<template>
  <div class="table-role">



    <vab-query-form>
      <vab-query-form-left-panel>
        <el-button icon="el-icon-plus" type="primary" @click="EditADD(0,'')">
          添加病区
        </el-button>


      </vab-query-form-left-panel>
      <vab-query-form-right-panel>


      </vab-query-form-right-panel>
    </vab-query-form>
    <el-dialog
      :title="planIsEdit ? '修改病区' : '添加病区'"
      :visible.sync="dialogFormVisible"
      width="500px"

    >

      <el-form ref="form" :model="form" :rules="rules"  label-width="80px">

        <el-form-item label="病区名称" prop="name">
          <el-input v-model.trim="form.name" autocomplete="off"></el-input>
        </el-form-item>
<!--        <el-form-item label="状态" prop="disabled" v-if="planIsEdit">-->
<!--          <el-select v-model="form.disabled" placeholder="请选择" style="width: 100%">-->
<!--            <el-option-->
<!--              v-for="item in options"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model.trim="form.remark" autocomplete="off" type="textarea"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="SaveAdd('form')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="分配房间"
      :visible.sync="dialogdfindroom"
      width="500px"
      @close='closeDialog'

    >

      <el-tree
        v-loading="Loading"
        v-if="dialogdfindroom"
        :data="data"
        show-checkbox
        :default-expanded-keys="expanded"
        :default-checked-keys="checked"
        node-key="lable"

        :props="defaultProps"
        ref="tree"
        :highlight-current="true"

      ></el-tree>
      <div slot="footer" class="dialog-footer">

        <el-button @click="dialogdfindroom=false">取 消</el-button>
        <el-button type="primary" @click="submitFormCheck">确 定</el-button>
      </div>
    </el-dialog>
    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"



    >


      <!--          <el-table-column show-overflow-tooltip label="账户名" width="200"  prop="institutionNumber">-->

      <!--          </el-table-column>-->
      <el-table-column
        show-overflow-tooltip
        label="病区编号"
        prop="inpNumber"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        label="病区名称"
        prop="name"
      ></el-table-column>
      <el-table-column
        show-overflow-tooltip
        label="状态"

      >

        <template slot-scope="scope">
          <span v-if="scope.row.disabled">禁用</span>
          <span v-if="!scope.row.disabled">启用</span>
        </template>
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        label="备注信息"
        prop="remark"

      ></el-table-column>


      <el-table-column
        show-overflow-tooltip
        label="操作"
        width="280px"
        fixed="right"
      >

        <template slot-scope="scope">
          <el-button type="text" @click="EditADD(scope.row.id, scope.row)">编辑</el-button>


          <el-button type="text" @click="tree(scope.$index, scope.row)" >

            分配房间
          </el-button>
          <el-button type="text" @click="del(scope.row.id, scope.row)">删除</el-button>
        </template>

      </el-table-column>
    </el-table>
  </div>
</template>

<script>
    import Print from '@/utils/print'
    import Vue from 'vue'
    Vue.use(Print)
    import { add,findall,search,resve,allotmentroom ,overallotmentroom,overfindotherinprooms,doDelete} from "@/api/hospital";
    import Template from "../../nursing/template";
    // let a = ['1001#1#1#101', '1002#2#1#102']
    export default {
        name: "Hospital",
        components: {Template},
        created() {
             this.search()
            let institutionNumber=localStorage.getItem("institutionNumber")
            // findall({institutionNumber}).then(res => {
            //     this.data = res.data
            //
            //
            // })
        },
        data(){
            return{
                dialogFormVisible:false,

                planIsEdit:false,
                dialogdfindroom:false,
                checked:[],
                id:0,
                data:[],
               a:[],
                Loading:false,
                expanded:[],
                options:[
                    {
                        value: true,
                        label: '禁用'
                    }, {
                        value: false,
                        label: '启用'
                    },
                ],
                listLoading:false,
                list:[],
                    allocation:{


                    inpNumber: "",
                institutionNumber: localStorage.getItem("institutionNumber"),
                rooms: [
                {
                    floor: '',
                    institutionNumber: '',
                    number: "",
                    roomCode: "",
                    unit: ''
                },
                    ]

            },
                form:{
                    institutionNumber: localStorage.getItem("institutionNumber"),
                    name: "",
                    remark: "",

                },
                rules:{
                    name: [
                        { required: true, message: '请输入病区名称', trigger: 'blur' },

                    ],
                },
                defaultProps: {
                    children: 'children',
                    label: 'labelName'
                }


            }
        },
        methods:{
            retun(data, id, indexArray){
                let arr = Array.from(indexArray)
                for (let i = 0, len = data.length; i < len; i++) {
                    arr.push(data[i])
                    if (data[i].lable === id) {
                        return arr
                    }
                    let children = data[i].children
                    if (children && children.length) {
                        let result = this.retun(children, id, arr)
                        if (result) return result
                    }
                    arr.pop()
                }
                return false
            },
            setdisabled(data){
                for(let i=0; i<data.length; i++){
                    let item = data[i]

                    if(this.a.includes(item.lable)){
                        item.disabled = true
                    }
                    if(item.children){
                        this.setdisabled(item.children)
                    }
                }
                return data
            },
             del(index,row){
                console.log(row)
                 let inpNumber=row.inpNumber
                 console.log(row)

                     this.$baseConfirm("你确定要删除当前项吗", null, async () => {
                         const {code, msg } = await doDelete(({inpNumber}));
                         if(code==200){
                             this.$baseMessage("删除成功");
                             this.search()
                         }else {
                             this.$baseMessage("删除失败");
                         }
                     });

             },
            tree(index,row) {

                console.log(row)
                this.allocation.inpNumber = row.inpNumber
                this.dialogdfindroom = true
                let inpNumber = row.inpNumber
                let institutionNumber = row.institutionNumber
                this.Loading=true
                findall({institutionNumber}).then(res => {

                    overfindotherinprooms({inpNumber, institutionNumber}).then(res1 => {


                        if (res1.data) {

                            const result = []
                            var getId = arr => {
                                arr.forEach(v => {
                                    if (v.children instanceof Array) {
                                        getId(v.children)
                                    } else {
                                        result.push((v.lable))
                                        this.expanded.push(v.lable)
                                    }
                                });
                            }
                            getId(res1.data);
                            console.log(result)
                            this.a = result

                            this.data = this.setdisabled(res.data)
                            this.Loading=false

                            console.log(this.data)
                            this.a.forEach(aa => {
                                console.log(aa)
                                let e = this.retun(this.data, aa, [])
                                console.log(e)
                                for (let i = e.length - 1; i >= 0; i--) {
                                    let item = e[i]
                                    if (item.disabled) {
                                        let itemp = e[i - 1]
                                        if (itemp && itemp.children.length == 1) {
                                            itemp.disabled = true
                                        }
                                    }
                                }
                            })
                            //选中
                            overallotmentroom({inpNumber, institutionNumber}).then(res2 => {

                                this.expanded = []
                                this.checked = []
                                if (res2.data) {
                                    const result2 = []
                                    var getId2 = arr => {
                                        arr.forEach(v => {
                                            if (v.children instanceof Array) {
                                                getId2(v.children)
                                            } else {
                                                result2.push((v.lable))
                                                this.expanded.push(v.lable)
                                            }
                                        });
                                    }
                                    getId2(res2.data);


                                    this.$refs.tree.setCheckedKeys(result2)

                                } else {

                                    this.$refs.tree.setCheckedKeys([])
                                    this.expanded = []
                                    this.checked = []
                                }


                            })




                        }else {

                            // this.data = this.setdisabled(res.data)
                             //选中
                            let institutionNumber=localStorage.getItem("institutionNumber")
                            findall({institutionNumber}).then(res => {
                                this.data = res.data
                                this.Loading=false
                                overallotmentroom({inpNumber, institutionNumber}).then(res2 => {


                                    if (res2.data) {
                                        const result2 = []
                                        var getId2 = arr => {
                                            arr.forEach(v => {
                                                if (v.children instanceof Array) {
                                                    getId2(v.children)
                                                } else {
                                                    result2.push((v.lable))
                                                    this.expanded.push(v.lable)
                                                }
                                            });
                                        }
                                        getId2(res2.data);


                                        this.$refs.tree.setCheckedKeys(result2)


                                    } else {

                                        this.$refs.tree.setCheckedKeys([])
                                        this.expanded = []
                                        this.checked = []
                                    }


                                })

                            })



                        }
                    })

                    })


                    // overfindotherinprooms({inpNumber,institutionNumber}).then(res => {
                    //     console.log(res.data)
                    //     if(res.data) {
                    //         const results = []
                    //         var getId = arr => {
                    //             arr.forEach(v => {
                    //                 if (v.children instanceof Array) {
                    //                     getId(v.children)
                    //
                    //                 } else {
                    //
                    //                     results.push((v.lable))
                    //
                    //
                    //                 }
                    //             });
                    //         }
                    //         getId(res.data);
                    //
                    //         console.log(results)
                    //     }
                    //
                    //
                    // })

                        // findall({institutionNumber}).then(res => {
                        //     this.data = res.data
                        //     const resultss=[]
                        //     var getIds = arrs => {
                        //         arrs.forEach(v => {
                        //             if (v.children instanceof Array) {
                        //                 getIds(v.children)
                        //
                        //             }else{
                        //
                        //                 resultss.push((v))
                        //
                        //             }
                        //         });
                        //     }
                        //     getIds(res.data);
                        //     overfindotherinprooms({inpNumber,institutionNumber}).then(res => {
                        //         if(res.data){
                        //             const results = []
                        //             var getIds = arrs => {
                        //                 arrs.forEach(v => {
                        //                     if (v.children instanceof Array) {
                        //                         getIds(v.children)
                        //
                        //                     }else{
                        //
                        //                         results.push((v.lable))
                        //
                        //                     }
                        //                 });
                        //             }
                        //             overallotmentroom({inpNumber,institutionNumber}).then(res => {
                        //
                        //                 this.expanded=[]
                        //                 this.checked=[]
                        //                 if(res.data){
                        //                     const result = []
                        //                     var getId = arr => {
                        //                         arr.forEach(v => {
                        //                             if (v.children instanceof Array) {
                        //                                 getId(v.children)
                        //                             }else{
                        //                                 result.push((v.lable))
                        //                                 this.expanded.push(v.lable)
                        //                             }
                        //                         });
                        //                     }
                        //                     getId(res.data);
                        //
                        //                     for(let i=0; i<resultss.length; i++){
                        //                         let item = resultss[i]
                        //                         if(results.includes(item.lable)){
                        //                             item.disabled = true
                        //                         }
                        //
                        //                     }
                        //                     console.log(this.data)
                        //                     this.$refs.tree.setCheckedKeys(result)
                        //
                        //                 }else {
                        //
                        //                     this.$refs.tree.setCheckedKeys([])
                        //                     this.expanded=[]
                        //                     this.checked=[]
                        //                 }
                        //
                        //
                        //
                        //
                        //             })
                        //             getIds(res.data);
                        //
                        //
                        //         }else {
                        //
                        //
                        //         }
                        //
                        //
                        //
                        //
                        //     })
                        //
                        //
                        //
                        // })


            },
            ddd(size){
                this.$print(this.$refs.print, { size })
            },
            submitFormCheck(){
                console.log(this.$refs.tree.getCheckedNodes(true))

                let arr = this.$refs.tree.getCheckedNodes(true)
                 console.log(arr.length)
                let a = []
                      arr.forEach(item => {
                          let b = item.lable
                          b=b.split('#')
                          a.push({
                              institutionNumber:localStorage.getItem("institutionNumber"),
                              number: b[0],
                              unit: b[1],
                              floor: b[2],
                              roomCode: b[3],
                          })
                      })

                      this.allocation.rooms=a


                console.log(this.allocation)
                allotmentroom(this.allocation).then(res => {
                    console.log(res.data)
                    if(res.code==200){
                        this.$baseMessage("分配成功",'success');
                        this.dialogdfindroom=false
                    }


                })
            },
            EditADD(id,data){
                  this.dialogFormVisible=true
                  this.id=id
                console.log(id)
                if(id==undefined){
                    console.log(data)
                    this.form={...data}
                    this.planIsEdit=true
                }else {
                   this.form.remark=""
                    this.form.name=""
                    this.planIsEdit=false
                }
            },
            SaveAdd(){

                this.$refs['form'].validate(async (valid) => {
                    if (valid) {
                        if(this.id==undefined){
                           this.form.disable= this.form.disabled
                            const {code} = await resve(this.form);
                            if(code==200){
                                this.$baseMessage("修改成功");
                                this.dialogFormVisible=false
                                this.search();

                            }else {
                                return false
                            }
                        }else{

                            console.log(this.form)
                            const {code} = await add(this.form);
                            if(code==200){
                                this.$baseMessage("添加成功");
                                this.search();
                                this.dialogFormVisible=false

                            }else {
                                return false
                            }
                        }




                    }
                    else {
                        return false;
                    }
                });



            },
            search(){
                let institutionNumber=localStorage.getItem("institutionNumber")
                search({institutionNumber}).then(res => {

                    this.list = res.data


                })
            },
            closeDialog(){
                // this.$refs.tree.setCheckedKeys([])

                this.expanded=[]



            },
        }
    }
</script>

<style scoped>



</style>
